<?php

namespace catchAdmin\registration\excel;

use app\common\lib\ZhyxMongo;
use catcher\library\excel\ExcelContract;
use MongoDB\BSON\UTCDateTime;
class FollowTaskExport implements ExcelContract
{
    /**
     * 设置头部
     *
     * @time 2020年09月08日
     * @return string[]
     */
    public function headers(): array
    {

        // TODO: Implement headers() method.
        return [
            "患者ID","单次就诊唯一标识号","就诊类型","就诊卡号","门诊号","病案号","住院号","姓名","性别","年龄（岁）","出生日期","随访流水号","随访方式","初治年龄","初治日期","随访周期","随访日期","随访状态代码","随访状态","身体状况","死亡日期","死亡原因","复发日期","复发诊断编码","复发诊断名称","首次复发转移日期","转移日期","转移部位","转移诊断编码","转移诊断名称","多原发诊断编码","多原发诊断名称","随访结论","证件类型","身份证号","现住址","联系电话","联系电话2","邮箱","微信","紧急联系人1","紧急联系人电话1","紧急联系人2","紧急联系人电话2","扩展字段1","扩展字段2","记录状态","不良反应"

        ];
    }

    /**
     * 处理数据
     *
     * @time 2020年09月08日
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @return array
     */
    public function sheets(): array
    {
        $req = request()->param();
        $pipLine = [
            ['$match' => [
                'pushtime' => ['$gte' => $req['dateTime'][0], '$lte' => $req['dateTime'][1]],
                'status' => 2,
                'resultIsEffective' => 1
            ]],
            ['$group' => [
                '_id' => '$patientId',
                'mode' => ['$last' => '$mode'],
                'followup_sn' => ['$last' => ['$toString' => '$_id']],
                'followup_datetime' => ['$last' => '$pushtime'],
                'followup_status_code' => ['$last' => '$result'],
                'followup_status' => ['$last' => '$resultName'],
                'type' => ['$last' => '$type'],
                'recur_datetime' => ['$last' => '$recurrence.checkTime'],
                'mets_datetime' => ['$last' => '$transfer.checkTime'],
                'mets_site' => ['$last' => '$transfer.place'],
                'health_status' => ['$last' => '$health_status'],
                'followup_conclusion' => ['$last' => '$followup_conclusion'],
                'adverse_reaction' => ['$last' => '$adverse_reaction']
            ]],
            ['$lookup' => [
                'from' => 'patient_info',
                'localField' => '_id',
                'foreignField' => 'patientId',
                'as' => 'info'
            ]],
            ['$unwind' => [
                'path' => '$info',
                'preserveNullAndEmptyArrays' => false
            ]],
            ['$addFields' => [
                'mz_count' => [
                    '$cond' => [
                        'if' => ['$ifNull' => ['$info.calc_date_node.visit_time_arr', false]],
                        'then' => ['$size' => '$info.calc_date_node.visit_time_arr'],
                        'else' => 0
                    ]
                ],
                'zy_count' => [
                    '$cond' => [
                        'if' => ['$ifNull' => ['$info.calc_date_node.inhospitalDateArr', false]],
                        'then' => ['$size' => '$info.calc_date_node.inhospitalDateArr'],
                        'else' => 0
                    ]
                ],
                'visit_type' => [
                    '$switch' => [
                        'branches' => [
                            ['case' => ['$eq' => ['$type', 1]], 'then' => '门诊'],
                            ['case' => ['$eq' => ['$type', 3]], 'then' => '住院']
                        ],
                        'default' => '住院'
                    ]
                ]
            ]],
            ['$match' => [
                'info.liveStatus' => ['$in' => ['0','1']],
                'info.is_in_hospital' => ['$in' => [1,2]]
            ]],
            ['$addFields' => [
                'calc_count' => [
                    '$cond' => [
                        'if' => ['$eq' => ['$type', 1]],
                        'then' => '$mz_count',
                        'else' => '$zy_count'
                    ]
                ],
                'age' => [
                    '$cond' => [
                        'if' => [
                            '$or' => [
                                ['$eq' => ['$info.birthdate', '']],
                                ['$eq' => ['$info.birthdate', ['$type' => 'missing']]],
                                ['$lt' => [['$strLenCP' => '$info.birthdate'], 10]]
                            ]
                        ],
                        'then' => 0,
                        'else' => [
                            '$subtract' => [
                                ['$year' => new UTCDateTime()],
                                ['$toInt' => ['$substr' => ['$info.patientId', 6, 4]]]
                            ]
                        ]
                    ]
                ]
            ]],
            ['$project' => [
                '_id' => false,
                'patient_id' => ['$ifNull' => ['$info.patient_id', '']],
                'visit_sn' => [
                    '$concat' => [
                        '$info.patient_id', '|',
                        ['$toString' => '$info.inList.inhospitalNo'], '|',
                        ['$toString' => '$calc_count'], '|',
                        '$visit_type'
                    ]
                ],
                'visit_type' => ['$ifNull' => ['$visit_type', '']],
                'visit_card_no' => ['$ifNull' => ['$info.visitcardno', '']],
                'outpatient_no' => ['$ifNull' => ['$info.outList.visitid', '']],
                'medical_record_no' => ['$ifNull' => ['$info.medicalRecordsNo', '']],
                'inpatient_no' => ['$ifNull' => ['$info.inList.inhospitalNo', '']],
                'name' => '$info.name',
                'gender' => ['$ifNull' => ['$info.sex', '']],
                'age' => '$age', // Include the modified age field here
                'date_of_birth' => '$info.birthdate',
                'followup_sn' => ['$ifNull' => ['$followup_sn', '']],
                'followup_method' => ['$ifNull' => ['$mode', '']],
                'first_treat_age' => ['$ifNull' => ['$info.first_treat_age', '']],
                'first_treat_datetime' => ['$ifNull' => ['$info.first_treat_datetime', '']],
                'followup_period' => '',
                'followup_datetime' => ['$ifNull' => ['$followup_datetime', '']],
                'followup_status_code' => ['$ifNull' => ['$followup_status_code', '']],
                'followup_status' => ['$ifNull' => ['$followup_status', '']],
                'health_status' => ['$ifNull' => ['$health_status', '']],
                'death_datetime' => ['$ifNull' => ['$info.death.deathDate', '']],
                'cause_of_death' => ['$ifNull' => ['$info.death.causeOfDeath', '']],
                'recur_datetime' => ['$ifNull' => ['$recur_datetime', '']],
                'recur_diag_code' => '',
                'recur_diag_name' => '',
                'first_recur_mets_date' => '',
                'mets_datetime' => ['$ifNull' => ['$mets_datetime', '']],
                'mets_site' => ['$ifNull' => ['$mets_site', '']],
                'mets_diag_code' => '',
                'mets_diag_name' => '',
                'mulpri_diag_code' => ['$ifNull' => [['$last' => '$info.bz.diagnoseArr.diseaseNo'], '']],
                'mulpri_diag_name' => ['$ifNull' => [['$last' => '$info.bz.diagnoseArr.diagnose'], '']],
                'followup_conclusion' => ['$ifNull' => ['$followup_conclusion', '']],
                'certificate_type' => '居民身份证',
                'certificate_no' => ['$ifNull' => ['$info.idno', '']],
                'current_address' => ['$ifNull' => ['$info.accountAddress', '']],
                'phone_no' => ['$ifNull' => ['$info.presentTelphone', '']],
                'phone_no2' => '',
                'email' => '',
                'weixin' => '',
                'contact_person1' => ['$ifNull' => ['$info.contactName', '']],
                'contact_phone_no1' => ['$ifNull' => ['$info.contactTelphone', '']],
                'contact_person2' => '',
                'contact_phone_no2' => '',
                'extend_data1' => '',
                'extend_data2' => '',
                'record_status' => '1',
                'adverse_reaction' => ['$ifNull' => ['$adverse_reaction', '']]
            ]]
        ];

        $result = ZhyxMongo::getInstance()->setCollection('follow_history')->aggregate($pipLine);
        $rst = [];
        $mode = config('dictionary.follow_mode');
        foreach($result as $k=>$v){
            $v["certificate_no"] = $v["certificate_no"]." ";

            if (isset($v['followup_datetime']) && !empty($v['followup_datetime'])) {
                $date1 = new \DateTime(date("Y-m-d"));
                $date2 = new \DateTime($v['followup_datetime']);
                $interval = $date1->diff($date2);
                $day = $interval->days;
                if ($day == 0) {
                    $day = 1;
                }
                $v["followup_period"] = $day;
            }else{
                $v["followup_period"] = 0;
            }

            if (in_array($v['followup_method'], [1,2,4])) {
                $v['followup_method'] = $mode[$v['followup_method']];
            }
            $rst[] = (array)$v;
        }
        return $rst;
    }
    public function setRow(): int
    {
        return 1;
    }
}